package com.gujiayue.common.interceptor;

import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.gujiayue.common.utils.JsonUtils;
import com.gujiayue.module.sys.pojo.SysPrivilegeRoleDo;
import com.gujiayue.module.sys.service.SecurityService;

/**
 * 安全元数据源
 */
@Component
public class SecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	
	//映射路径
	AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	@Resource
	private SecurityService securityService;

	@Override
	public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
		// 获取请求地址
		String requestUrl = ((FilterInvocation) o).getRequestUrl();
		System.out.println("requestUrl-->"+requestUrl);
		// 查询具体某个接口的权限
		List<SysPrivilegeRoleDo> privilegeRoleList =securityService.getPrivilegeRoleList();
        System.out.println(JsonUtils.obeyJson(privilegeRoleList));
		for (SysPrivilegeRoleDo privilege: privilegeRoleList){
            if (antPathMatcher.match(privilege.getPrivilegeUrl(), requestUrl)){
            	List<String> codeList=privilege.getCodeList();
                return SecurityConfig.createList(codeList.toArray(new String[codeList.size()]));
            }
        }
        // 没有匹配上的，只要登录之后就可以访问.
        return SecurityConfig.createList(new String[] {"Y0000"});
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> aClass) {
		return true;
	}
}
